import mysql.connector
from mysql.connector import pooling, Error
import logging
import os

# 配置日志记录
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 创建连接池
db_config = {
    'host': os.getenv('DB_HOST', 'localhost'),
    'port': os.getenv('DB_PORT', '3434'),
    'user': os.getenv('DB_USER', 'root'),
    'password': os.getenv('DB_PASSWORD', '123456'),
    'database': os.getenv('DB_DATABASE', 'pythonsql')
}

connection_pool = pooling.MySQLConnectionPool(
    pool_name="mypool",
    pool_size=5,
    **db_config
)

def get_db_connection():
    """
    获取数据库连接
    """
    try:
        cnx = connection_pool.get_connection()
        if cnx.is_connected():
            logger.info("成功从连接池获取连接")
            return cnx
        else:
            logger.error("从连接池获取的连接无效")
            return None
    except Error as err:
        logger.error(f"Error: {err}")
        return None